package com.xasxt.book.app.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.xasxt.book.app.entity.Role;
import com.xasxt.book.app.entity.User;
import com.xasxt.book.app.service.UserService;
public class MyRealm extends AuthorizingRealm {
	@Autowired
	private UserService userService;
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		SimpleAuthenticationInfo  info=null;  
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("email", (String)token.getPrincipal());
		User user=login(map);
		if(user!=null) {
			Subject suject=SecurityUtils.getSubject();
			Session session=	suject.getSession();
			session.setAttribute("user", user);//将当前登录用户存到shiro定义的session中
			info= new SimpleAuthenticationInfo(user.getEmail(),user.getAccount(),getName());
		}
		return info;
	}
	private User login(Map<String, Object> map) {
		return userService.login(map);
	}



	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("email", (String)principals.getPrimaryPrincipal());
		SimpleAuthorizationInfo   info=new SimpleAuthorizationInfo();
		User user=login(map);
		List<String>rolesNames=new ArrayList<String>();//装载角色名称
		if(user!=null) {
			List<Role>list=user.getListRole();
			if(list!=null) {
				if(list.size()>0) {
					for(Role r:list) {
						rolesNames.add(r.getrName());
					}
				}
			}
		}
		info.addRoles(rolesNames);
		return info;
	}

}
